import axios from "axios";
import router from "@/router";
import merge from 'lodash/merge'
import { clearLoginInfo } from '@/utils'
import qs from 'qs'
//import { getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import VueCookies from 'vue-cookies'


const http = axios.create({
    timeout: 1000*30,
    withCredentials:true,
    headers:{
        'Content-Type':'application/json;charset=utf-8',
        'Access-Control-Allow-Origin':'*'
    }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config =>{
    // 请求头带上token
    //config.headers['Authorization'] = getCurrentInstance().appContext.config.globalProperties.$cookies.get('Authorization')
    config.headers['Authorization'] = VueCookies.get('Authorization')
    return config
}, error => {
    return Promise.reject(error)
})


/**
 * 响应拦截
 */
http.interceptors.response.use( repsonse=>{
    if(repsonse.status == 200){
        return repsonse.data
    }
    return repsonse
}, error=>{
    console.log('响应', error)
    ElMessage({message:error.message, type:'error', duration: 1500})
    switch( error.repsonse.status){
        case 400:
            ElMessage({message:error.repsonse.data, type:'error', duration: 1500})
            break;
        case 401:
            clearLoginInfo()
            router.push({name:'login'})
            break;            
        case 405:
            ElMessage({message:'http请求方式有误', type:'error', duration: 1500})
            break;            
        case 500:
            ElMessage({message:'服务器出了点小差，请稍后再试', type:'error', duration: 1500})
            break
    }
    return Promise.reject(error)
})


/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName)=>{
  // 非生产环境 && 开启代理, 接口前缀统一使用[/proxyApi/]前缀做代理拦截!    
    return (import.meta.env.MODE !== 'production' && import.meta.env.VITE_OPEN_PROXY? import.meta.env.VITE_PROXY : import.meta.env.VITE_APP_BASE_API) + actionName
}


/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefaultParams = true) =>{
    var defaults = {
        't':new Date().getTime()
    }
    return openDefaultParams ? merge(defaults, params):params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data={}, openDefaultdata=true, contentType = 'json') =>{
    var defaults ={
        't':new Date().getTime()
    }
    data = openDefaultdata?merge(defaults, data):data
    return contentType === 'json'?JSON.stringify(data):qs.stringify(data)
}

export default http
